package com.your.package.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.your.package.network.ApiService
import com.your.package.utils.EmailUtils
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class LoginViewModel(
    private val apiService: ApiService,
    private val userDao: UserDao
) : ViewModel() {
    private val _loginState = MutableStateFlow<LoginState>(LoginState.Idle)
    val loginState: StateFlow<LoginState> = _loginState

    fun login(email: String, password: String) {
        viewModelScope.launch {
            try {
                _loginState.value = LoginState.Loading

                // 1. 从本地数据库获取用户信息
                val user = userDao.getUserByEmail(email)
                if (user == null || user.password != password) {
                    _loginState.value = LoginState.Error("邮箱或密码错误")
                    return@launch
                }

                // 2. 验证融云用户信息
                val response = apiService.getRongCloudUserInfo(user.rongCloudId)
                if (!response.isSuccessful || response.body()?.code != 200) {
                    _loginState.value = LoginState.Error("融云用户验证失败")
                    return@launch
                }

                // 3. 登录成功
                _loginState.value = LoginState.Success(user)
            } catch (e: Exception) {
                _loginState.value = LoginState.Error(e.message ?: "登录失败")
            }
        }
    }
}

sealed class LoginState {
    object Idle : LoginState()
    object Loading : LoginState()
    data class Success(val user: User) : LoginState()
    data class Error(val message: String) : LoginState()
} 